from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from datetime import datetime
import hashlib
import uuid

from ..schemas.cep import CEPRequest, CEPResponse
from ..core.tcp_client import send_xml_request
from ..core.xml_builder import build_request_xml, parse_response_xml
from ..core.utils import format_error_msg, ERROR_CODES
from ..config import settings
from ..core.logger import log_transaction
from ..core.database import get_db
from ..models.transaction import Transaction

router = APIRouter()

def calculate_md5(data: dict) -> str:
    """计算交易数据的MD5值（大写）"""
    # 按字段名升序排序并拼接
    sorted_items = sorted(
        [(k, v) for k, v in data.items() if v is not None and k != "md5"],
        key=lambda x: x[0]
    )
    content = "".join(f"{k}={v}" for k, v in sorted_items)
    return hashlib.md5(content.encode('utf-8')).hexdigest().upper()

@router.post("/cep", response_model=CEPResponse)
async def cep_transaction(request: CEPRequest, db: Session = Depends(get_db)):
    """
    CEP 消费交易
    
    Args:
        request: CEP 交易请求
    
    Returns:
        CEP 交易响应
    """
    try:
        # 准备请求数据（自动补充必要字段）
        request_data = request.prepare_data()
        
        # 生成系统内部orderid（不同于pay_order）
        now = datetime.now()
        request_data["orderid"] = f"01{now.strftime('%Y%m%d%H%M%S')}243"  # 01 + 时间戳 + 243(随机后缀)
        
        # 构建 XML 请求报文（带 MD5 签名）
        request_xml = build_request_xml(request_data, need_md5=True)
        
        # 发送请求并接收响应
        response_xml = await send_xml_request(request_xml)
        
        # 解析响应（验证 MD5 签名）
        response_data = parse_response_xml(response_xml, verify_md5=True)
        
        # 添加错误信息
        response_data["error_msg"] = format_error_msg(
            response_data.get("resp_code", "9999"),
            ERROR_CODES
        )
        
        response = CEPResponse(**response_data)
        
        # 保存交易记录到数据库
        transaction = Transaction(
            id=str(uuid.uuid4()),
            trans_code="CEP",
            pan=request.pan,
            trans_amt=request.trans_amt,
            trans_date=response.bank_date,
            trans_time=datetime.now().strftime("%H%M%S"),
            trans_sn=response.trans_sn,
            rrn=response.rrn,
            orderid=response.orderid,
            resp_code=response.resp_code,
            bank_date=response.bank_date,
            merno=request.merno,
            terminal=request.terminal,
            pay_order=request.pay_order  # 保存外部订单号
        )
        db.add(transaction)
        db.commit()
        
        # 记录交易日志
        log_transaction(
            trans_type="CEP",
            direction="INFO",
            message=f"Transaction completed: {response.trans_sn}",
            orderid=response.orderid,
            pan=request.pan
        )
        
        return response
        
    except Exception as e:
        # 记录错误并返回统一的错误响应
        error_response = CEPResponse(
            resp_code="9999",
            trans_sn="",
            bank_date=request_data.get("trans_date", ""),
            rrn="",
            orderid=request_data.get("orderid", ""),
            pan=request.pan,
            error_msg=str(e)
        )
        
        # 记录错误日志
        log_transaction(
            trans_type="CEP",
            direction="ERROR",
            message=str(e),
            orderid=request_data.get("orderid", ""),
            pan=request.pan
        )
            
        return error_response 